import { useEffect } from "react";
import useAppleStore from "../store/useAppleStore";
import {useShallow} from 'zustand/react/shallow';
import {useAtom} from 'zustand/react/useAtom';

//https://juejin.cn/post/7452175687089946659 文档
const Child1 = () => {
    const {foodName, price, count, getAmount, addCount, removeCount,doubleCount,setColor} = useAppleStore();
    // console.log('Child1-render');
    return (
       <>
        <div>食物名称: {foodName}</div>
        <div>单价: {price} 元</div>
        <div>数量: {count} 个</div>
        <div>金额: {getAmount()} 元</div>

        <button onClick={addCount}>数量加1</button>
        <button onClick={removeCount}>数量减1</button>
        <button onClick={doubleCount}>数量乘2</button>

        <button onClick={setColor.bind(null, 'blue')}>修改颜色</button>
       </>
    )
}

const Child2 = () => {
    // 解决性能问题 useShallow 浅比较 只有当color发生变化时才会重新渲染 否则不会重新渲染。
    // 但是如果color是一个对象，那么还是会重新渲染，所以如果color是一个对象，那么可以使用useAtom来解决。
    const {color} = useAppleStore(useShallow(state =>({
        color: state.color
    })));
    console.log('Child2-render');
    return (
        <div>
            <hr />
            <h1 style={{color: color}}>color: {color}</h1>
        </div>
    )
}

const MyZustand = () => {
    return <>
        <Child1/>
        <Child2/>
    </>
}

export default MyZustand;